package com.kuaiyin.util;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JmxVariableConverter {

    // 匹配 {{ token }} 或 {{ $uuid }} 格式
    private static final Pattern TEMPLATE_PATTERN = Pattern.compile("\\{\\{\\s*(\\$?\\w+)\\s*}}");
    private static final Random random = new Random();

    /**
     * 替换变量模板为 JMeter 可识别格式
     * @param input 原始字符串，如 {"token": "{{ token }}", "name": "{{ $name }}"}
     * @return 替换后的字符串
     */
    public static String convertTemplate(String input) {
        if (input == null || input.isEmpty()) return input;

        Matcher matcher = TEMPLATE_PATTERN.matcher(input);
        StringBuffer sb = new StringBuffer();  // 用于存储替换后的结果

        while (matcher.find()) {
            String rawKey = matcher.group(1); // token 或 $uuid
            String replacement;

            if (rawKey.startsWith("$")) {
                // 内置函数：$uuid -> UUID
                replacement = convertFunction(rawKey.substring(1));
            } else {
                // 普通变量：token -> ${token}
                replacement = "${" + rawKey + "}";
            }

            matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
        }

        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 支持的内置函数映射
     * - 原生 JMeter 函数使用 ${__XXX}
     * - 不支持的自定义函数预生成真实值
     */
    private static String convertFunction(String funcName) {
        return switch (funcName) {
            case "uuid" -> "${__UUID}";
            case "timestamp" -> "${__time}";
            case "randomInt" -> "${__Random(10000,99999)}";
            case "alphanumeric" -> "${__RandomString(8,abcdefghijklmnopqrstuvwxyz0123456789)}";

            // ❗ 下面两个 JMeter 不支持的自定义函数，直接生成真实值写死
            case "phone" -> generatePhoneNumber();
            case "name" -> generateChineseName();

            // 兜底（如果你手动写了自定义函数 jar）
            default -> "${__" + funcName + "}";
        };
    }

    private static String generatePhoneNumber() {
        String[] prefixes = {"139", "138", "137", "136", "135", "159", "158", "157", "188", "187"};
        String prefix = prefixes[random.nextInt(prefixes.length)];
        String suffix = String.format("%08d", random.nextInt(100000000));
        return prefix + suffix;
    }

    private static String generateChineseName() {
        String[] firstNames = {"张", "李", "王", "赵", "刘", "陈", "杨", "黄"};
        String[] secondNames = {"伟", "芳", "娜", "敏", "静", "强", "磊", "丽"};
        return firstNames[random.nextInt(firstNames.length)] + secondNames[random.nextInt(secondNames.length)];
    }
}
